#include "putpackageform.h"
#include "ui_putpackageform.h"
#include <QFileDialog>
#include <QTextStream>
#include <QDebug>
#include <QListView>
#include <QFileSystemModel>

PutPackageForm::PutPackageForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PutPackageForm)
{
    ui->setupUi(this);

    terminal = new TerminalForm();
    connParam = new ConnectParamForm();
    ui->horizontalLayout_terminal->addWidget(terminal);
    ui->horizontalLayout_connparam->addWidget(connParam);
}

PutPackageForm::~PutPackageForm()
{
    delete ui;
}

void PutPackageForm::listView_updateScript()
{
    ui->listWidget_script->clear();
    qDebug() << "listView_updateScript" << fileName;
    QFile dataFile(fileName);
    if (dataFile.open(QFile::ReadOnly|QIODevice::Text))
    {
        QTextStream data(&dataFile);
        QString line;
        while (!data.atEnd())//逐行读取文本，并去除每行的回车
        {
            line = data.readLine();
            line.remove('\n');
            ui->listWidget_script->addItem(line);//把各行添加到listwidget
        }
        ui->statusBar->setText("文件加载成功:" + fileName);
    }
    else
    {
        ui->statusBar->setText("文件打开失败:" + fileName);
    }
}

void PutPackageForm::treeView_updateFolder()
{
    //显示本地的目录结构
    QString _logDir = folderName;
    QFileSystemModel *fileModel = new QFileSystemModel();
    fileModel->setRootPath(QDir::currentPath());

    ui->treeView_folder->setModel(fileModel);
    ui->treeView_folder->setRootIndex(fileModel->index(_logDir));

    //隐藏文件名后面的信息
    for(int i = 1; i < fileModel->columnCount(); i++)
    {
        ui->treeView_folder->setColumnHidden(i, true);
    }
}


void PutPackageForm::pushButton_FolderSelect_OnClicked()
{
    ui->statusBar->setText("打开文件夹: 选择包文件夹");
    folderName = QFileDialog::getExistingDirectory(this, "choose folder", "/");
    ui->lineEdit_PackageFolderPath->setText(folderName);
    ui->statusBar->setText("选择的文件夹: "+folderName);
    treeView_updateFolder();
}

void PutPackageForm::pushButton_FileSelect_OnCliecked()
{
    fileName = QFileDialog::getOpenFileName(this, tr("Open Script"), ".", tr("Script File(*.*)"));
    ui->statusBar->setText("选择的脚本:" + fileName);
    ui->lineEdit_ScriptPath->setText(fileName);
    qDebug() << "pushButton_FileSelect_OnCliecked:" << fileName;
    listView_updateScript();
}

void PutPackageForm::pushButton_RunScript()
{
    ui->statusBar->setText("执行脚本:" + fileName);

    terminal->run_cmdstr("lftp");
    ui->statusBar->setText("执行脚本:lftp");

    for( int i = 0; i < ui->listWidget_script->count(); i++ )
    {
        terminal->run_cmdstr(ui->listWidget_script->item(i)->text());
        qDebug() << ui->listWidget_script->item(i)->text();
    }

    terminal->run_cmdstr("quit");
    ui->statusBar->setText("执行脚本:exit");
}
